package ru.nsu.ccfit.kalah.database;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import ru.nsu.ccfit.kalah.game.Score;

import java.util.ArrayList;
import java.util.List;

public class DatabaseManager {
    public static void insertScore(Context context, Score score) {
        DatabaseHelper helper = new DatabaseHelper(context);
        SQLiteDatabase database = helper.getWritableDatabase();

        ContentValues values = new ContentValues();
        values.put("player1", score.getFirstPlayer());
        values.put("player2", score.getSecondPlayer());
        values.put("result1", score.getFirstScore());
        values.put("result2", score.getSecondScore());
        database.insert("results", null, values);
        database.close();
        helper.close();
    }

    public static List<Score> selectAll(Context context) {
        DatabaseHelper helper = new DatabaseHelper(context);
        SQLiteDatabase database = helper.getWritableDatabase();

        List<Score> scores = new ArrayList<Score>();

        Cursor cursor = database.query("results", new String[]{"_id","player1", "player2", "result1", "result2"}, null, null, null, null, null);

        cursor.moveToFirst();
        while (!cursor.isAfterLast()) {

            Score score = new Score();
            score.setId(cursor.getLong(cursor.getColumnIndex("_id")));
            score.setFirstPlayer(cursor.getString(cursor.getColumnIndex("player1")));
            score.setSecondPlayer(cursor.getString(cursor.getColumnIndex("player2")));
            score.setFirstScore(cursor.getInt(cursor.getColumnIndex("result1")));
            score.setSecondScore(cursor.getInt(cursor.getColumnIndex("result2")));

            scores.add(score);

            cursor.moveToNext();
        }

        cursor.close();

        database.close();
        helper.close();

        return scores;
    }

}
